package com.dubious.interview.euler;

import java.math.BigInteger;


public class Problem20 {

    /**
     * Find the sum of the digits in the number X!
     */
    public static int run(int base)
    {
        // calculate the factorial from the base
        BigInteger factorial = factorial(base);
        
        // sum the digits
        String factorialAsString = factorial.toString();
        int sumOfDigits = 0;
        for(int i = 0; i < factorialAsString.length(); i++)
        {
            sumOfDigits += Integer.parseInt(factorialAsString.substring(i, i+1));
        }
        
        return sumOfDigits;
    }
    
    private static BigInteger factorial(int base)
    {
        BigInteger factorial = new BigInteger("1");
        for(int i = 2; i <= base; i++)
        {
            factorial = factorial.multiply(new BigInteger(Integer.valueOf(i).toString()));
        }
        
        return factorial;
    }
}
